package com.iot08.api.service.supplement;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.iot08.api.config.redis.RedisClusterService;
import com.iot08.api.service.*;
import com.iot08.api.vo.request.AddHealthfunctionReqVO;
import com.iot08.api.vo.request.GetHealthfunctionHistoryReqVO;
import com.iot08.api.vo.request.GetHealthfunctionReqVO;
import com.iot08.common.constant.Const;
import com.iot08.common.constant.ConstCacheField;
import com.iot08.common.constant.ConstKafka;
import com.iot08.common.entity.app.AnimalHeatSetting;
import com.iot08.common.entity.app.BloodOxygenSetting;
import com.iot08.common.entity.app.BloodPressureSetting;
import com.iot08.common.entity.app.HeartRateSetting;
import com.iot08.common.utils.DateUtil;
import com.iot08.common.utils.StringUtil;
import com.iot08.common.utils.response.ResponseEnum;
import com.iot08.common.utils.response.ResponseMap;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @version 1.0
 * @Description:
 * @time: 2021/3/8 18:51
 * @author: Rock
 */
@Service
@Slf4j
public class HealthService {

    @Resource
    private HeartRateRecordService heartRateRecordService;
    @Resource
    private HeartRateSettingService heartRateSettingService;
    @Resource
    private BloodPressureRecordService bloodPressureRecordService;
    @Resource
    private BloodPressureSettingService bloodPressureSettingService;
    @Resource
    private BloodOxygenSettingService bloodOxygenSettingService;
    @Resource
    private BloodOxygenRecordService bloodOxygenRecordService;
    @Resource
    private AnimalHeatSettingService animalHeatSettingService;
    @Resource
    private AnimalHeatRecordService animalHeatRecordService;
    @Resource
    private RedisClusterService redisClusterService;
    @Resource
    private KafkaService kafkaService;

    private static List<Integer> healthFrequencyList = new ArrayList<>();

    static {
        healthFrequencyList.add(-1);
        healthFrequencyList.add(10);
        healthFrequencyList.add(30);
        healthFrequencyList.add(60);
    }

    /**
     * 健康功能(心率/血压/血氧) 获取数据
     * @param imei
     * @param vo
     * @time: 2021/3/8 18:56
     * @author: Rock
     * @version 1.0
     */
    public ResponseMap getHealthfunction(String imei, GetHealthfunctionReqVO vo) {
        ResponseMap res = ResponseMap.success();
//        //默认是关闭的
//        String currentValue = "0";
//        Long currentValueTime = 0l;
//        String todayStr = DateUtil.dateToStr(new Date(), DateUtil.FORMAT_4);
//        if ("heartRate".equals(vo.getCmd())) {
//            //心率
//            res.put("normalRangeV", "60~100");
//            HeartRateSetting setting = heartRateSettingService.getById(imei, vo.getOpenid());
//            res.put("setFrequency", setting.getSetFrequency());
//            if (setting.getCurrentValue() != null) {
//                currentValue = setting.getCurrentValue();
//            }
//            if (setting.getCurrentValueTime() != null) {
//                currentValueTime = setting.getCurrentValueTime();
//            }
//            res.put("todayDatas", heartRateRecordService.listData(imei, todayStr));
//        } else if ("bloodPressure".equals(vo.getCmd())) {
//            //血压， 收缩压/舒张压/脉搏数
//            res.put("normalRangeV", "90~139|60~89");
//            BloodPressureSetting setting = bloodPressureSettingService.getById(imei, vo.getOpenid());
//            res.put("setFrequency", setting.getSetFrequency());
//            if (setting.getCurrentValue() != null) {
//                currentValue = setting.getCurrentValue();
//            }
//            if (setting.getCurrentValueTime() != null) {
//                currentValueTime = setting.getCurrentValueTime();
//            }
//            res.put("todayDatas", bloodPressureRecordService.listData(imei, todayStr));
//        } else if ("bloodOxygen".equals(vo.getCmd())) {
//            //血氧
//            res.put("normalRangeV", "70~100");
//            BloodOxygenSetting setting = bloodOxygenSettingService.getById(imei, vo.getOpenid());
//            res.put("setFrequency", setting.getSetFrequency());
//            if (setting.getCurrentValue() != null) {
//                currentValue = setting.getCurrentValue();
//            }
//            if (setting.getCurrentValueTime() != null) {
//                currentValueTime = setting.getCurrentValueTime();
//            }
//            res.put("todayDatas", bloodOxygenRecordService.listData(imei, todayStr));
//        } else if ("animalHeat".equals(vo.getCmd())) {
//            //体温
//            res.put("normalRangeV", "36~37.2");
//            AnimalHeatSetting setting = animalHeatSettingService.getById(imei, vo.getOpenid());
//            res.put("setFrequency", setting.getSetFrequency());
//            if (setting.getCurrentValue() != null) {
//                currentValue = setting.getCurrentValue();
//            }
//            if (setting.getCurrentValueTime() != null) {
//                currentValueTime = setting.getCurrentValueTime();
//            }
//            res.put("todayDatas", animalHeatRecordService.listData(imei, todayStr));
//        } else {
//            return ResponseMap.fail(ResponseEnum.STATUS403.getCode(), "cmd参数不正确");
//        }
//        res.put("cmd", vo.getCmd());
//        res.put("currentValue", currentValue);
//        res.put("currentValueTime", currentValueTime);
//        res.put("frequencyList", healthFrequencyList);

        String CMD = vo.getCmd().toUpperCase();
        if ("heart".toUpperCase().equals(CMD)) {
            //获取心率
            HeartRateSetting setting = heartRateSettingService.getById(imei, vo.getOpenid());
            if (vo.getDate() == null) {
                res.put("lastData", setting.getLastHeart());
                res.put("lastDataTime", setting.getLastDataTime());
                res.put("frequency", setting.getHeartFreq());
                res.put("switchStatus", setting.getSwitchStatus());
                return res;
            }
            JSONObject dataListDict = new JSONObject();
            if (vo.getStartDate() == null) {
                vo.setStartDate(vo.getDate());
            }
            if(vo.getDate().equals(vo.getStartDate())){
                // 通过日期找出当天所有心率记录
                List<JSONObject> objects = heartRateRecordService.listDataWithDay(imei, vo.getDate());
                res.put("lastData", setting.getLastHeart());
                res.put("lastDataTime", setting.getLastDataTime());
                res.put("frequency", setting.getHeartFreq());
                res.put("switchStatus", setting.getSwitchStatus());
                res.put("upper", setting.getUpper());
                res.put("lower", setting.getLower());
                //赋值 字典 嵌套 数组
                JSONArray tempArr = new JSONArray();
                tempArr.addAll(objects);
                dataListDict.put(vo.getDate(), tempArr);
                res.put("dataListDict", dataListDict);

            }else{
                //起始天数不同的 暂无
                res.put("lastData", setting.getLastHeart());
                res.put("lastDataTime", setting.getLastDataTime());
                res.put("frequency", setting.getHeartFreq());
                res.put("switchStatus", setting.getSwitchStatus());
                res.put("upper", setting.getUpper());
                res.put("lower", setting.getLower());
                //赋值 空字典 嵌套 数组

                dataListDict.put(vo.getDate(), new JSONArray());
                res.put("dataListDict", dataListDict);
                return res;
            }

        }else if ("temperature".toUpperCase().equals(CMD)) {
            //获取体温
            AnimalHeatSetting setting = animalHeatSettingService.getById(imei, vo.getOpenid());
            if (vo.getDate() == null) {
                res.put("lastData", setting.getLastTemperature());
                res.put("lastDataTime", setting.getLastDataTime());
                return res;
            }
            JSONObject dataListDict = new JSONObject();
            if (vo.getStartDate() == null) {
                vo.setStartDate(vo.getDate());
            }
            if(vo.getDate().equals(vo.getStartDate())){
                // 通过日期找出当天所有心率记录
                List<JSONObject> objects = animalHeatRecordService.listDataWithDay(imei, vo.getDate());
                res.put("lastData", setting.getLastTemperature());
                res.put("lastDataTime", setting.getLastDataTime());
                res.put("frequency", setting.getTemperatureFreq());
                res.put("switchStatus", setting.getSwitchStatus());
                res.put("upper", setting.getUpper());
                res.put("lower", setting.getLower());
                //赋值 字典 嵌套 数组
                JSONArray tempArr = new JSONArray();
                tempArr.addAll(objects);
                dataListDict.put(vo.getDate(), tempArr);
                res.put("dataListDict", dataListDict);

            }else{
                //起始天数不同的 暂无
                res.put("lastData", setting.getLastTemperature());
                res.put("lastDataTime", setting.getLastDataTime());
                res.put("frequency", setting.getTemperatureFreq());
                res.put("switchStatus", setting.getSwitchStatus());
                res.put("upper", setting.getUpper());
                res.put("lower", setting.getLower());
                //赋值 空字典 嵌套 数组

                dataListDict.put(vo.getDate(), new JSONArray());
                res.put("dataListDict", dataListDict);
                return res;
            }
        }

        return res;
    }

    /**
     * 健康功能(心率/血压/血氧) 设置数据
     * @param imei
     * @param vo
     * @time: 2021/3/9 9:41
     * @author: Rock
     * @version 1.0
     */
    public ResponseMap setHealthfunction(String imei, AddHealthfunctionReqVO vo) {
        ResponseMap res = ResponseMap.success();
//        int downFrequency = 0;
//        if (healthFrequencyList.contains(vo.getSetFrequency())) {
//            if (vo.getSetFrequency() == -1) {
//                downFrequency = 0;
//            } else if (vo.getSetFrequency() > 0) {
//                downFrequency = vo.getSetFrequency() * 60;
//                if (downFrequency < 300) {
//                    downFrequency = 300;
//                }
//            }
//        } else {
//            if (new Integer(0).equals(vo.getSetFrequency())) {
//                //立即测量
//                downFrequency = 2;
//            } else {
//                return ResponseMap.fail(ResponseEnum.STATUS403.getCode(), "setFrequency参数不正确");
//            }
//        }
//        String cmdType = "";
//        if ("heartRate".equals(vo.getCmd())) {
//            //获取一下，没有记录则会创建
//            heartRateSettingService.getById(imei, vo.getOpenid());
//            cmdType = ConstKafka.DEVICE_TYPE_setHeartRate;
//        } else if ("bloodPressure".equals(vo.getCmd())) {
//            bloodPressureSettingService.getById(imei, vo.getOpenid());
//            cmdType = ConstKafka.DEVICE_TYPE_setBP;
//        } else if ("bloodOxygen".equals(vo.getCmd())) {
//            bloodOxygenSettingService.getById(imei, vo.getOpenid());
//            cmdType = ConstKafka.DEVICE_TYPE_setBO;
//        } else if ("animalHeat".equals(vo.getCmd())) {
//            animalHeatSettingService.getById(imei, vo.getOpenid());
//            cmdType = ConstKafka.DEVICE_TYPE_setBodyTemperature;
//        } else {
//            return ResponseMap.fail(ResponseEnum.STATUS403.getCode(), "cmd参数不正确");
//        }
//        JSONObject dataPush = new JSONObject();
//        dataPush.put("cmdType", cmdType);
//        dataPush.put("frequency", downFrequency);
//        if ("-1".equals(vo.getFrequency())) {
//            //立即测量
//            String onlineStatus = redisClusterService.hget(imei, ConstCacheField.ONLINE_STATUS);
//            if (!"1".equals(onlineStatus)) {
//                return ResponseMap.fail(ResponseEnum.STATUS5001.getCode(), ResponseEnum.STATUS5001.getMsg());
//            }
//            dataPush.put("openid", vo.getOpenid());
//        } else {
//            Update update = new Update();
//            update.set("setFrequency", vo.getFrequency());
//            update.set("openid", vo.getOpenid());
//            update.set("setChangeTime", System.currentTimeMillis() / 1000);
//            if (ConstKafka.DEVICE_TYPE_setHeartRate.equals(cmdType)) {
//                heartRateSettingService.updateById(imei, update);
//            } else if (ConstKafka.DEVICE_TYPE_setBP.equals(cmdType)) {
//                bloodPressureSettingService.updateById(imei, update);
//            } else if (ConstKafka.DEVICE_TYPE_setBO.equals(cmdType)) {
//                bloodOxygenSettingService.updateById(imei, update);
//            } else if (ConstKafka.DEVICE_TYPE_setBodyTemperature.equals(cmdType)) {
//                animalHeatSettingService.updateById(imei, update);
//            }
//        }
//        kafkaService.emitDeviceDemand(imei, cmdType, dataPush, vo.getOpenid());
//        res.put("cmd", vo.getCmd());
//        return res;
        //log.info("请求参数："+vo);
        if (vo.getCmd().contains("set")) {
            //是否在线
            String onlineStatus = redisClusterService.hget(imei, ConstCacheField.ONLINE_STATUS);
            if (!"1".equals(onlineStatus)) {
                return ResponseMap.fail(ResponseEnum.STATUS5001.getCode(), ResponseEnum.STATUS5001.getMsg());
            }
            // 获取设备的心率/体温频率设置
            String devFreType = "temperatureFreq";
            // 内部协议设置心率/体温频率 的指令
            String cmdSetType = "setBodyTemperature";
            if (vo.getCmd().toUpperCase().contains("heart".toUpperCase())) {
                //心率
                devFreType = "heartFreq";
                cmdSetType = ConstKafka.DEVICE_TYPE_setHeartRate;
            }
            log.info("devFreType类型："+devFreType);
            log.info("cmd:{}, 开关switch:{} " ,vo.getCmd(), vo.getSwitchStatus());

            String devFre = "120";

            if (vo.getSwitchStatus() != null) {
                JSONObject dataPush = new JSONObject();
                dataPush.put("cmdType", cmdSetType);
                // 设置开关的状态
                if (devFreType.contains("heart")) {
                    //获取心率
                    HeartRateSetting setting = heartRateSettingService.getById(imei, vo.getOpenid());
                    setting.setSwitchStatus(vo.getSwitchStatus());
                    devFre = setting.getHeartFreq();
                    if(vo.getSwitchStatus() == 1){
                        dataPush.put("frequency", Integer.valueOf(devFre) * 60 );
                        //dataPush.put("frequency", Integer.valueOf(devFre) );
                    } else {
                        dataPush.put("frequency", 0);
                    }
                    kafkaService.emitDeviceDemand(imei, cmdSetType, dataPush, vo.getOpenid());
                    heartRateSettingService.save(setting);
                }else{
                    //获取体温
                    AnimalHeatSetting setting = animalHeatSettingService.getById(imei, vo.getOpenid());
                    setting.setSwitchStatus(vo.getSwitchStatus());
                    devFre = setting.getTemperatureFreq();
                    if(vo.getSwitchStatus() == 1){
                        dataPush.put("frequency", Integer.valueOf(devFre) * 60 );
                    } else {
                        dataPush.put("frequency", 0);
                    }
                    kafkaService.emitDeviceDemand(imei, cmdSetType, dataPush, vo.getOpenid());
                    animalHeatSettingService.save(setting);
                }
            }else {
                int frequency = 0;
                if (vo.getFrequency() != null) {
                    frequency = Integer.valueOf(vo.getFrequency());
                }
                if ((frequency < 30 || frequency > 240) && frequency != -1) {
                    // 请输入30~240分钟内 API.request.setHealth.frequencyError
                    return ResponseMap.fail(ResponseEnum.STATUS400.getCode(),"API.request.setHealth.frequencyError");
                }
                // 设置频率
                // 先判断现有的 开关状态
                int switchStatus = 0;
                Object setting = null;
                String tempFreq = null;
                if (devFreType.contains("heart")) {
                    //获取心率配置
                    HeartRateSetting tempSetting = heartRateSettingService.getById(imei, vo.getOpenid());
                    switchStatus = tempSetting.getSwitchStatus();
                    tempFreq = tempSetting.getHeartFreq();
                    setting = tempSetting;
                }else{

                    //获取体温配置
                    AnimalHeatSetting tempSetting = animalHeatSettingService.getById(imei, vo.getOpenid());
                    switchStatus = tempSetting.getSwitchStatus();
                    tempFreq = tempSetting.getTemperatureFreq();
                    setting = tempSetting;
                }
                JSONObject kafkaData = new JSONObject();
                kafkaData.put("type", cmdSetType);
                if (frequency == -1) {
                    //立即查询一次
                    if (switchStatus == 1) {
                        kafkaData.put("frequency", 2);
                        //tempFreq 是分钟 下发时单位是: 秒
                        kafkaData.put("devFreq", Integer.valueOf(tempFreq) * 60);
                        //kafkaData.put("devFreq",tempFreq);
                    }else{
                        kafkaData.put("frequency", 1);
                    }
                    kafkaService.emitDeviceDemand(imei, cmdSetType, kafkaData, vo.getOpenid());
                }else{
                    if (switchStatus == 1) {
                        //开关为 1 的情况下才下发, 其余不下发
                        kafkaData.put("frequency", frequency * 60);
                        //kafkaData.put("frequency", frequency);
                        kafkaService.emitDeviceDemand(imei, cmdSetType, kafkaData,vo.getOpenid());
                    }
                    Update update = new Update();
                    if (setting.getClass().equals(HeartRateSetting.class)){
                        update.set("heartFreq", ""+frequency);
                        heartRateSettingService.updateById(imei, update);
                    }else{
                        update.set("temperatureFreq", ""+frequency);
                        animalHeatSettingService.updateById(imei, update);
                    }
                }
            }
        }
        return res;
    }

    /**
     * @param imei
     * @param vo
     * @time: 2021/3/9 10:25
     * @author: Rock
     * @version 1.0
     */
    public ResponseMap getHealthfunctionHistory(String imei, GetHealthfunctionHistoryReqVO vo) {
        ResponseMap res = ResponseMap.success();
        if (!DateUtil.isDate(vo.getDate())) {
            return ResponseMap.fail(ResponseEnum.STATUS403.getCode(), "date参数不正确");
        }
        if ("heartRate".equals(vo.getCmd())) {
            //心率
            res.put("datas", heartRateRecordService.listDataWithDay(imei, vo.getDate()));
        } else if ("bloodPressure".equals(vo.getCmd())) {
            //血压， 收缩压/舒张压
            res.put("datas", bloodPressureRecordService.listData(imei, vo.getDate()));
        } else if ("bloodOxygen".equals(vo.getCmd())) {
            //血氧
            res.put("datas", bloodOxygenRecordService.listData(imei, vo.getDate()));
        } else if ("animalHeat".equals(vo.getCmd())) {
            //体温
            res.put("datas", animalHeatRecordService.listDataWithDay(imei, vo.getDate()));
        } else {
            return ResponseMap.fail(ResponseEnum.STATUS403.getCode(), "cmd参数不正确");
        }
        res.put("date", vo.getDate());
        return res;
    }
}
